#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

typedef struct ListNode {
	int val;
	struct ListNode* next;
}ListNode;

ListNode* initialList(int val)
{
	ListNode* head = (ListNode*)malloc(sizeof(ListNode));
	head->val = val;
	head->next = NULL;
	return head;
}

void addList(ListNode* head, int val) {
	ListNode* newList = (ListNode*)malloc(sizeof(ListNode));
	newList->next = NULL;
	newList->val = val;
	while (head->next)
	{
		head = head->next;
	}
	head->next = newList;
}

void freeList(ListNode* head) {
	ListNode* next = NULL;
	while (head)
	{
		next = head->next;
		free(head);
	}
	freeList(next);
}

void printList(ListNode* head) {
	printf("[");
	while (head)
	{
		printf(" %d ", head->val);
		head = head->next;
	}
	printf("]\n");
}

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
	ListNode* head3 = (ListNode*)malloc(sizeof(ListNode));
	head3->next = NULL;
	int muls1 = 1;
	int muls2 = 1;
	int val1 = 0;
	int val2 = 0;
	while (l1) {
		val1 += (l1->val) * muls1;
		l1 = l1->next;
		muls1 *= 10;
	}
	while (l2) {
		val2 += (l2->val) * muls2;
		l2 = l2->next;
		muls2 *= 10;
	}
	int count = 0;
	int ret = val1 + val2;
	int tmp = ret;
	if (tmp)
	{
		while (tmp > 0)
		{
			count++;
			tmp /= 10;
		}
	}
	else
		count = 1;
	ListNode* cur = (ListNode*)malloc(sizeof(ListNode));
	cur = head3;
	int i = 0;
	for (; i < count; i++)
	{
		ListNode* newList = (ListNode*)malloc(sizeof(ListNode));
		if (count > 1)
		{
			if (i < count - 1)
			{
				newList->next = NULL;
				cur->next = newList;
			}
		}
		int val3 = ret % 10;
		cur->val = val3;
		cur = cur->next;
		ret /= 10;
	}
	return head3;
}

int main()
{
	ListNode* head1 = initialList(0);
	ListNode* head2 = initialList(0);
	ListNode* head3 = addTwoNumbers(head1, head2);
	printList(head3);
	free(head1);
	free(head2);
	free(head3);
	return 0;
}